package com.tasly.attendance.manager.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.tasly.attendance.domain.AttendanceAnalyse;
import com.tasly.attendance.domain.AttendanceFileParse;
import com.tasly.attendance.domain.impl.AttendanceAnalyseImpl;
import com.tasly.attendance.domain.impl.AttendanceFileParseImpl;
import com.tasly.attendance.entity.AttendanceRecordEntity;
import com.tasly.attendance.entity.DayHoursEntity;
import com.tasly.attendance.io.AttendanceFileReader;
import com.tasly.attendance.manager.AttendanceManager;
import com.tasly.attendance.view.AttendanceResultView;
import com.tasly.attendance.view.impl.AttendanceResultTxtFileViewImpl;

public class AttendanceManagerImpl implements AttendanceManager {

    private static final AttendanceManager manager = new AttendanceManagerImpl();
    private static AttendanceFileParse attendanceFileParser = AttendanceFileParseImpl.getInstance();
     
    private AttendanceManagerImpl() {
    }
           
    public static AttendanceManager getInstance() {
        return manager;
    }

    @Override
    public boolean processAttendanceTxtFile(File orignalFilePath, File generatedFileFolderPath, Integer month) {
        // TODO make file path configurable
        AttendanceFileReader readerHolder = new AttendanceFileReader(orignalFilePath);
        BufferedReader reader = readerHolder.getAttendanceFileReader();
        AttendanceAnalyse analyser = new AttendanceAnalyseImpl();
        String tmpLine = null;
        if (reader != null) {
            boolean isBreakLoop = true;
            do {
                try {
                    tmpLine = reader.readLine();
                } catch (IOException e) {
                    System.out.println("Exception happened when try to read one line!!");
                }
                if (tmpLine == null || tmpLine.trim().length() == 0) {
                    // if arrive to last line, break loop
                    isBreakLoop = false;
                } else {
                    //invoke domain logic to parse the lines in txt file
                    attendanceFileParser.parseLine(tmpLine);
                }
            } while (isBreakLoop);
        }
        //the data struture has been set up after loop
        //start process
        //TODO: invoke analytic method, make month can be configurable
        //the second param is used to limit the month should be processed.
        //testing start......
        Date inputDate = new Date();
        Calendar calendar = Calendar.getInstance();
        try {
            //TODO: change the fixed date below
            calendar.setTime(inputDate);
            calendar.set(Calendar.MONTH, month-1);
            calendar.set(Calendar.DAY_OF_MONTH, 1);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 1);
            inputDate = calendar.getTime();
        } catch (Exception e) {
            System.out.println("date parse  error!!");
            return false;
        }
        //testing end.....
        //prepare data
        Map<String, List<AttendanceRecordEntity>> orignalMap = analyser
                .prepareData(attendanceFileParser.getAttendanceRecordsMap(),
                        inputDate);
        //display the original data
        //analyse the original data
        Map<String, List<DayHoursEntity>> analysedMap = analyser.analyse(
                attendanceFileParser.getAttendanceRecordsMap(), inputDate);
        //TODO: write the analysed data to the file
        //prepare output result
        AttendanceResultView viewer = AttendanceResultTxtFileViewImpl.getInstance();
//        viewer.viewOriginalData(orignalMap, new File("/Users/sam/Downloads/orignal.txt"));
//        viewer.viewAnalysedData(analysedMap, new File("/Users/sam/Downloads/analysed.txt"));
        //log generate file date time
        Date generateFileDate = new Date();
        SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyyMMdd");
        viewer.viewOriginalData(orignalMap,
                new File(generatedFileFolderPath.getAbsoluteFile() + "/orignal_datetime_"
                        + outputDateFormat.format(generateFileDate) + ".txt"));
        viewer.viewAnalysedData(analysedMap,
                new File(generatedFileFolderPath.getAbsoluteFile() + "/analyse_result_"
                        + outputDateFormat.format(generateFileDate) + ".txt"));
        return true;
    }

}
